import java.io.*;
import java.net.*;

public class multithreadudpserver {
	public static void main(String[] args) {

		DatagramSocket socket = null;
		DatagramPacket packet = null;
		int port = 2345;

		try {
			socket = new DatagramSocket(port);
			byte[] message = new byte[1000];
			packet = new DatagramPacket(message, message.length);

			int counter = 0;
			while (true) {
				try {
					socket.receive(packet);
					myTask task = new myTask(socket, packet);
					Thread thread = new Thread(task);
					thread.start(); 
					counter++;
					
					System.out.println("thread number: "+counter);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} finally{
			socket.close();
		}
	}

	static class myTask implements Runnable {

		private DatagramSocket socket;
		private DatagramPacket packet;

		public myTask(DatagramSocket s, DatagramPacket p) {
			this.socket = s;
			this.packet = p;
		}


		@Override
		public void run() {
			try {
				byte[] message = new byte[1000];
				message = this.packet.getData();
				System.out.println("from udpclient: " + new String(packet.getData()));
				this.packet = new DatagramPacket(message, message.length, this.packet.getAddress(), this.packet.getPort());
				this.socket.send(packet);

			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}